package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginParamVo;
import com.atguigu.gmall.user.vo.LoginRespVo;
import com.atguigu.starter.cache.service.CacheService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
* @author lfy
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2023-07-28 09:38:42
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    CacheService cacheService;

    @Override
    public LoginRespVo login(LoginParamVo paramVo, String ipAddress) {
        UserInfo info = lambdaQuery()
                .eq(UserInfo::getLoginName, paramVo.getLoginName())
                .eq(UserInfo::getPasswd, MD5.encrypt(paramVo.getPasswd()))
                .one();

        if(info != null){
            //登录成功
            LoginRespVo vo = new LoginRespVo();

            //1、准备令牌
            String token = UUID.randomUUID().toString();
            vo.setToken(token);
            vo.setNickName(info.getNickName());

            info.setIpAddress(ipAddress);
            //2、保存令牌和用户信息的对应关系
            cacheService.save(RedisConst.LOGIN_USER +token, info,7*24*3600L);

            return vo;
        }

        //登录失败，全局异常处理
        throw new GmallException(ResultCodeEnum.LOGIN_FAILED_ACCOUNT_PWD_ERROR);
    }

    @Override
    public void logout(String token) {

        cacheService.delete(RedisConst.LOGIN_USER+token);
    }
}




